/**
 * 数字转换为字符串前面补上0
 */
function numAddZero(number: number, length = 2) {
  const strNum: string = String(number);
  switch (strNum.length < length) {
    case true:
      return new Array(length).join("0") + strNum;
    case false:
      return strNum;
  }
}

class Time {
  hour: number;
  minute: number;
  second: number;
  millisecond: number;
  timer: number;

  /**
   * 初始化
   */
  constructor(
    time = {
      hour: 0,
      minute: 0,
      second: 0,
      millisecond: 0,
    }
  ) {
    console.log("初始化时间");
    this.hour = time.hour;
    this.minute = time.minute;
    this.second = time.second;
    this.millisecond = time.millisecond;
    this.timer = -1;
  }

  /**
   * 初始化计时器
   */
  initTimer() {
    this.timer = window.setInterval(this.startTimer.bind(this), 50);
  }

  /**
   * 开始计时
   */
  startTimer() {
    console.log("开始计时");
    this.millisecond += 50;
    if (this.millisecond >= 1000) {
      this.millisecond = 0;
      this.second = this.second + 1;
    }
    if (this.second >= 60) {
      this.second = 0;
      this.minute = this.minute + 1;
    }
    if (this.minute >= 60) {
      this.minute = 0;
      this.hour = 1;
    }
    this.millisecond += 10;
  }

  /**
   * 暂停计时
   */
  pauseTimer() {
    console.log("暂停时间");
    clearInterval(this.timer);
  }

  /**
   * 重置计时
   */
  resetTimer() {
    console.log("重置时间");
    this.hour = 0;
    this.minute = 0;
    this.second = 0;
    this.millisecond = 0;
    clearInterval(this.timer);
  }

  /**
   * 判断超时
   */
  judgeTimer() {
    console.log("判断是否超时一个小时");
  }

  /**
   * 格式化输出小时
   */
  formatHour(length = 2) {
    const doubleHour = numAddZero(this.hour, length);
    return doubleHour;
  }

  /**
   * 格式化输出秒
   */
  formatMinute(length = 2) {
    const doubleMinute = numAddZero(this.minute, length);
    return doubleMinute;
  }

  /**
   * 格式化输出f
   */
  formatSecond(length = 2) {
    const doubleSecond = numAddZero(this.second, length);
    return doubleSecond;
  }

  /**
   * 格式化输出毫秒
   */
  formatMillSecond(length = 2) {
    const doubleMillSecond = numAddZero(
      Math.round(this.millisecond / 10),
      length
    );
    return doubleMillSecond;
  }

  /**
   * 输出为字符串
   */
  toString(length = 2) {
    const doubleHour = this.formatHour(length);
    const doubleMinute = this.formatMinute(length);
    const doubleSecond = this.formatSecond(length);
    const doubleMillSecond = this.formatMillSecond(length);
    return `${doubleHour}:${doubleMinute}:${doubleSecond}:${doubleMillSecond}`;
  }
}

export default Time;
